<template>
    <CustomTable ref="ruleTableRef" rowKey="id" size="small" :rules="tableRules" :columns="tableColumns" :data-source="proList" :pagination="false">
        <template #title>
            <slot name="title" />
        </template>
        <template #customRateTitle>
            <flexbox>
                <span>质量评分</span>
                <a-tooltip>
                    <template #title>
                        <div>
                            <div>1.需求说明：需求说明应清晰完整，简洁易于理解</div>
                            <div>2.原型：原型应符合规范</div>
                            <div>3.拆分颗粒度：拆分颗粒度应符合团队管理要求</div>
                        </div>
                    </template>
                    <QuestionCircleOutlined class="margin-l-8" style="cursor: pointer" />
                </a-tooltip>
            </flexbox>
        </template>
        <template #requireType="{ record }">
            <h-product-type :type="$filters.valToNameFilter('requireType', record.requireType)" />
        </template>
        <template #level="{ record }">
            <h-level :level="record.level" v-if="record.level" />
        </template>
        <template #requireDescShow="{ record }">
            <!-- <a-tooltip v-if="record.requireDescShow">
                <template #title>
                    <div v-html="record.requireDescShow.replace(/<img(?:.|\s)*?>/g, '')"></div>
                </template>
                <div class="require-desc-text" v-html="record.requireDescShow.replace(/<img(?:.|\s)*?>/g, '')" />
            </a-tooltip> -->
            <a-tooltip :title="setText(record.requireDescShow)">
                <div class="text-bre2">{{ setText(record.requireDescShow) }}</div>
            </a-tooltip>
        </template>
        <template #jiraUrl="{ record }">
            <a @click="jumpTo(record.jiraUrl)" v-if="record.jiraUrl">{{ $filters.jiraUrlFilter(record.jiraUrl) }}</a>
        </template>
        <template #productDoc="{ record, index }">
            <flexbox>
                <a-textarea
                    placeholder="请输入评审意见限制200个字"
                    v-model:value="record.verOpinion"
                    :maxlength="200"
                    auto-size
                    @change="handleTextChange($event, index)"
                    v-if="canEditOpinion"
                />
                <span class="opinion-cont" v-html="record.verOpinion" v-else />
                <flexbox class="margin-l-8" style="width: 100px" v-if="canEditOpinion">
                    <a @click="handleClear(index)" :class="['margin-l-8', record.verOpinion ? 'canEdit' : 'disabledEdit']" v-if="record.verOpinion"
                        >清空</a
                    >
                </flexbox>
            </flexbox>
        </template>
        <template #pmpProductScoreDTO="{ record, index }">
            <flexbox>
                <span style="width: 70px; color: #8590a5">需求说明</span>
                <a-rate
                    allow-half
                    style="margin-bottom: 4px"
                    :value="record.pmpProductScoreDTO ? record.pmpProductScoreDTO.requestDesc : 0"
                    @change="handleRateChange($event, 'requestDesc', index)"
                />
                <span style="margin-left: 6px; color: #8590a5">{{ record.pmpProductScoreDTO ? record.pmpProductScoreDTO.requestDesc || 0 : 0 }}</span>
            </flexbox>
            <flexbox>
                <span style="width: 70px; color: #8590a5">原型</span>
                <a-rate
                    allow-half
                    style="margin-bottom: 4px"
                    :value="record.pmpProductScoreDTO ? record.pmpProductScoreDTO.prototype : 0"
                    @change="handleRateChange($event, 'prototype', index)"
                />
                <span style="margin-left: 6px; color: #8590a5">{{ record.pmpProductScoreDTO ? record.pmpProductScoreDTO.prototype || 0 : 0 }}</span>
            </flexbox>
            <flexbox>
                <span style="width: 70px; color: #8590a5">拆分颗粒度</span>
                <a-rate
                    allow-half
                    style="margin-bottom: 4px"
                    :value="record.pmpProductScoreDTO ? record.pmpProductScoreDTO.splitGranularity : 0"
                    @change="handleRateChange($event, 'splitGranularity', index)"
                />
                <span style="margin-left: 6px; color: #8590a5">{{
                    record.pmpProductScoreDTO ? record.pmpProductScoreDTO.splitGranularity || 0 : 0
                }}</span>
            </flexbox>
        </template>
        <template #action="{ record }">
            <a @click="showDetail(record.id)">详情</a>
        </template>
    </CustomTable>
</template>

<script lang="ts">
import { HLevel, HProductType, CustomTable } from '@/components';
import { useRouter } from 'vue-router';
import api from '@/api';
import { QuestionCircleOutlined } from '@ant-design/icons-vue';
import { deepClone } from '@/utils/util';
import { message } from 'ant-design-vue';
import { defineComponent, ref, unref, computed, watch } from 'vue';
export default defineComponent({
    components: {
        HLevel,
        HProductType,
        CustomTable,
        QuestionCircleOutlined
    },
    props: {
        disabled: {
            type: Boolean,
            default: false
        },
        list: {
            type: Array,
            default: () => []
        },
        stepStatus: {
            type: String,
            default: ''
        }
    },
    emits: ['deleteHandle', 'success', 'syncData'],
    setup(props, { emit }) {
        const router = useRouter();
        const ruleTableRef = ref<any>();
        const proList = ref<Recordable>([]);
        const validateRate = (rule: any, value: any) => {
            if (value) {
                const { requestDesc, prototype, splitGranularity } = value;
                return requestDesc && prototype && splitGranularity ? Promise.resolve() : Promise.reject();
            } else {
                return Promise.reject();
            }
        };
        const tableRules = {
            pmpProductScoreDTO: [
                { required: true, message: '质量评分不能为空' },
                {
                    validator: validateRate,
                    message: '需求说明，原型和拆分颗粒度都不能为空'
                }
            ]
        };
        const tableColumns = computed(() => {
            const tableColumns: Recordable[] = [
                {
                    title: '产品需求名称',
                    dataIndex: 'requireName',
                    ellipsis: true,
                    width: '25%'
                },
                {
                    title: '需求描述',
                    dataIndex: 'requireDescShow',
                    slots: { customRender: 'requireDescShow' },
                    // ellipsis: true,
                    width: 100
                },
                {
                    dataIndex: 'pmpProductScoreDTO',
                    slots: { title: 'customRateTitle', customRender: 'pmpProductScoreDTO' },
                    width: 300
                }
            ];
            if (unref(canShowOpinion)) {
                tableColumns.push({
                    title: '评审意见',
                    dataIndex: 'productDoc',
                    width: 400,
                    slots: { customRender: 'productDoc' }
                });
            }
            return [
                ...tableColumns,
                {
                    title: '操作',
                    key: 'action',
                    width: 60,
                    slots: { customRender: 'action' },
                    align: 'center'
                }
            ];
        });
        // 只有产品内部评审和产品经理修改阶段可以显示逐条批注
        const canShowOpinion = computed(() => {
            return ['productAudit', 'productChange', 'devReview'].includes(props.stepStatus);
        });
        // 只有产品内部评审阶段可以进行逐条批注
        const canEditOpinion = computed(() => {
            return ['productAudit', 'devReview'].includes(props.stepStatus) && !props.disabled;
        });
        const showDetail = (id: number) => {
            router.push({
                path: '/productRequire/productDetail',
                query: {
                    id
                }
            });
        };
        const jumpTo = (link) => {
            window.open(link, '_blank');
        };
        const handleSave = async (index: number) => {
            const query = {
                ...proList.value[index],
                businessChange: true
            };
            const { success } = await api.productRequireModel.updateProduct([query]);
            if (success) {
                message.success('操作成功');
            }
        };
        const handleClear = (index: number) => {
            proList.value[index].verOpinion = '';
            handleSave(index);
        };
        const handleTextChange = () => {
            emit('syncData', proList.value);
        };
        const handleRateChange = (val, field, index) => {
            const pmpProductScoreDTO = proList.value[index].pmpProductScoreDTO || {};
            pmpProductScoreDTO[field] = val;
            proList.value[index].pmpProductScoreDTO = pmpProductScoreDTO;
            emit('syncData', proList.value);
        };
        const validate = async () => {
            let res = true;
            // 内部评审需要校验
            if (props.stepStatus === 'productAudit') {
                if (unref(ruleTableRef)) {
                    res = await unref(ruleTableRef).validate();
                    // 滚动到提示位置
                    if (!res) {
                        unref(ruleTableRef).$el.scrollIntoView({
                            block: 'center',
                            behavior: 'smooth'
                        });
                    }
                    return res;
                } else {
                    return true;
                }
            } else {
                return true;
            }
        };
        const setText = (html) => {
            let txt: any = document.createElement('div');
            txt.innerHTML = html;
            const content = txt.innerText || txt.textContent;
            txt = null;
            return content;
        };
        watch(
            () => props.list,
            (n) => {
                proList.value = n ? deepClone(n) : [];
            },
            { immediate: true }
        );
        return {
            ruleTableRef,
            proList,
            tableColumns,
            canShowOpinion,
            canEditOpinion,
            showDetail,
            jumpTo,
            handleSave,
            handleClear,
            handleTextChange,
            validate,
            tableRules,
            handleRateChange,
            setText
        };
    }
});
</script>

<style scoped lang="less">
::v-deep(.ant-table-row) {
    p {
        margin: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
}
.canEdit {
    cursor: pointer;
    color: @primary-color;
}
.disabledEdit {
    cursor: not-allowed;
    color: @disable-font-color;
}
.opinion-cont {
    white-space: pre-wrap;
    color: @error-color;
}
</style>